<?php

/*请求日志*/
if (! function_exists('create_log')) {
    function create_log($str, string $type = 'test')
    {
        $str = is_array($str) ? json_encode($str, JSON_UNESCAPED_UNICODE) : $str;
        $log_path = public_path("log/{$type}");
        if (! is_dir($log_path)) {
            mkdir($log_path, 0777, true);
            chmod($log_path,0755);
        }

        $log_name = $log_path.'/'.date('Ymd').'.log';
        $url      = isset($_SERVER['REDIRECT_URL']) ? trim($_SERVER['REDIRECT_URL']) : request()->getRequestUri();
        $log_str  = date('Y-m-d H:i:s').'  '.$url.'  '.$str."\r\n\r\n";
        file_put_contents($log_name, $log_str, FILE_APPEND);
    }
}

if (! function_exists('get_menu_tree')) {
    function get_menu_tree(array $data, $pid = 0) :array
    {
        $result = [];
        foreach ($data as $k => $v) {
            if ($v['pid'] == $pid) {
                $child = get_menu_tree($data, $v['id']);
                if (!empty($child)) {
                    $v['child'] = $child;
                }
                $result[] = $v;
                unset($data[$k]);
            }
        }
        return $result;
    }
}

/**
 * 获取 模块/控制器/方法
 * @param string type
 */
if (! function_exists('get_controller_action')) {
    function get_controller_action($type = 'url')
    {
        $route = Route::currentRouteAction();
        $route_list = explode('\\', $route);

        $module = strtolower($route_list[count($route_list)-2]);
        list($Controller, $Action) = explode('Controller@', end($route_list));

        return  ($type == 'url')
            ? strtolower($module.'/'.$Controller.'/'.$Action)
            : ['model' => $module, 'controller' => strtolower($Controller), 'action' => strtolower($Action)];
    }
}